package com.example.mybatis.business.impl;

import com.example.mybatis.business.IExcelBusiness;
import com.example.mybatis.dao.ICityDao;
import com.example.mybatis.dao.IUserDao;
import com.example.mybatis.model.CityTO;
import com.example.mybatis.model.UserTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class ExcelBusiness implements IExcelBusiness {

    @Autowired
    private IUserDao userDao;

    @Autowired
    private ICityDao cityDao;

    @Override
    public String importExcelResolvedData(Map<String, List<?>> dataMap) throws Exception{
        List<UserTO> userTOList = (List<UserTO>) dataMap.get("userInfo");
        List<CityTO> cityTOList = (List<CityTO>) dataMap.get("province_cities");
        List<String> userAccounts = new ArrayList<>();
        userTOList.stream().forEach((item)->{
            userAccounts.add(item.getUserAccount());
        });
        List<String> existAccounts = userDao.queryExistUserAccounts(userAccounts);
        List<UserTO> insertUsers = new ArrayList<>();
        List<UserTO> updateUsers = new ArrayList<>();
        userTOList.forEach((item)->{
            if(existAccounts.contains(item.getUserAccount())){ //用户名已存在则放入待更新列表，否则放入待插入列表
                updateUsers.add(item);
            }else{
                if(!StringUtils.isEmpty(item.getUserAccount())){
                    insertUsers.add(item);
                }
            }
        });
        List<String> cityCodes = new ArrayList<>();
        cityTOList.stream().forEach((item)->{
            cityCodes.add(item.getCityCode());
        });
        List<String> existCityCodes = cityDao.queryExistCityCodes(cityCodes);
        List<CityTO> addCityTOS = new ArrayList<>();
        List<CityTO> updateCityTOS = new ArrayList<>();
        cityTOList.stream().forEach((item)->{
            if(!existCityCodes.contains(item.getCityCode())){ //城市代码已存在则放入更新列表，否则放入添加列表
                addCityTOS.add(item);
            }else{
                if(!StringUtils.isEmpty(item.getCityCode())){
                    updateCityTOS.add(item);
                }
            }
        });
        if(insertUsers.size()>0){
            userDao.batchAddUserInfo(insertUsers);
        }
        if(updateUsers.size()>0){
            userDao.batchUpdateUserInfo(updateUsers);
        }
        if(addCityTOS.size()>0){
            cityDao.batchAddCities(addCityTOS);
        }
        if(updateCityTOS.size()>0){
            cityDao.batchUpdateCities(updateCityTOS);
        }
        return "import Excel success";
    }
}
